package top.toptimus.util;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.util.Map;
import java.util.ResourceBundle;

public class ResourcesUtil {

    /**
     * 保存全局属性值
     */
    private static Map<String, String> map = Maps.newHashMap();
    /**
     * 属性文件加载对象
     */
    private static PropertiesLoader resources = new PropertiesLoader("dict.properties");

    /**
     * get value from local property file, format value : {0},{1}
     *
     * @param fileName
     * @param section
     * @param values
     * @return
     * @throws Exception
     */
    public static String getFormatProperties(String fileName, String section, String[] values) throws Exception {

        String retValue;
        try {
            ResourceBundle rb = ResourceBundle.getBundle(fileName);
            retValue = (String) rb.getObject(section);
            MessageFormat form = new MessageFormat(retValue);
            retValue = form.format(values);
        } catch (Exception e) {
            throw new Exception(e);
        }
        return retValue;
    }

    /**
     * 获取配置
     *
     * @see ${fns:getConfig('adminPath')}
     */
    public static String getConfig(String key) {
        String value = map.get(key);
        if (value == null) {
            value = resources.getProperty(key);
            map.put(key, value != null ? value : StringUtils.EMPTY);
        }
        return value;
    }


}
